using System;
using System.Collections;
using System.Data;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Policy;
using PHSRAG.Security.Enumerations;
using PHSRAG.Utility;

namespace PHSRAG.Insight21.Admin
{
    /// <summary>
    /// Displays labs basic information and Members of the lab.
    /// </summary>
    public partial class AdminLabAcess : BasePage
    {
        #region Constants

        /// <summary>The table in the datacontainer containing the lab member information. </summary>
        private const string LabAccessTableName = "Access";

        #endregion

        #region Private Variables

        /// <summary>Policy used for caching business objects.</summary>
        private ICachePolicy objectCachePolicy;

        /// <summary>Policy used for caching objects to be used across pages. </summary>
        private ICachePolicy pageCachePolicy;

        #endregion

        #region Private Properties

        /// <summary>
        /// Gets the Lab whose access is viewed. Checks the cache first, if empty
        /// retrieves it from the database.
        /// </summary>
        private Lab CurrentLab
        {
            get
            {
                Lab lab = objectCachePolicy.GetCachedObject(Lab.CacheKey) as Lab;
                if (lab == null)
                {
                    lab = new Lab(objectCachePolicy);
                    Hashtable incomingData = (Hashtable) pageCachePolicy.GetCachedObject(Keys.IncomingDataKey);
                    lab.Load(DataAccess.GetConnectionString(), Convert.ToInt32(incomingData[Keys.LabIdKey]));
                    lab.Cache();
                    pageCachePolicy.UnCache(Keys.IncomingDataKey);
                }
                return lab;
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Sets lab basic information controls (name, description and organization)
        /// and also loads the data grid and adds window open code for edit button.
        /// </summary>
        /// <param name="sender">The object raising the event.</param>
        /// <param name="e">Information about the event itself.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            breadCrumb.Add("Access", "AdminLabAccess.aspx", Settings.GetKeyValue("BreadCrumb.DetailPageLevel", 2));

            if (!IsPostBack)
            {
                const string popUpFeatures = "width=600,height=400,scrollbars=no,resizable=yes,status=no";
                const string wizardHostPage = "EditAdminLabAccessWizard.aspx";
                editLab.Attributes["onclick"] = string.Format("window.open('{0}', 'EditLabWizard', '{1}');return false;",
                    wizardHostPage, popUpFeatures);

                Lab lab = CurrentLab;
                LoadLabBasicInfoControls(lab);
                LoadDataGrid(lab);
                SetLabAccessRightsCheckBoxes(lab);
            }
        }

        /// <summary>
        /// Sets up the lab member name on the datagrid.
        /// </summary>
        /// <param name="sender">The object raising the event.</param>
        /// <param name="e">Information about the event itself.</param>
        protected void OnItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                DataRowView view = (DataRowView) e.Item.DataItem;
                ((Label) e.Item.FindControl("memberName")).Text = view["PIName"].ToString();
            }
        }

        /// <summary>
        /// Resets the subnavigation selected link(s) before the 
        /// header performs a redirect.
        /// </summary>
        /// <param name="sender">Control which rasied the event.</param>
        /// <param name="e">Arguments associated with the event.</param>
        protected void OnHeaderNavigate(object sender, CommandEventArgs e)
        {
            adminSubNavigation.Reset();
            adminLabManagementSubNavigation.Reset();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Sets the lab name, description and organization labels.
        /// </summary>
        /// <param name="lab">Lab whose details are being displayed.</param>
        private void LoadLabBasicInfoControls(Lab lab)
        {
            labName.Text = lab.Name;
            labDescription.Text = lab.Description;
            labOrganization.Text = lab.Organization;
        }

        /// <summary>
        /// Loads lab members into the datagrid.
        /// </summary>
        /// <param name="lab">Lab whose details are being displayed.</param>
        private void LoadDataGrid(Lab lab)
        {
            labAccess.DataSource = lab.GetDataContainer().Tables[LabAccessTableName];
            labAccess.DataBind();
        }

        /// <summary>
        /// Sets the access rights checkboxes based on lab's access rights currently set
        /// for the lab.
        /// </summary>
        private void SetLabAccessRightsCheckBoxes(Lab lab)
        {
            DataRowCollection accessRows = lab.GetDataContainer().Tables[LabAccessTableName].Rows;
            if (accessRows.Count != 0)
            {
                object labRightsBitMask = accessRows[0]["RightBitMask"]; // same access rights for all lab members
                if (labRightsBitMask != DBNull.Value)
                {
                    viewFinInfo.Checked =
                        ((int) labRightsBitMask & (int) AccessRightBit.ViewFinancialInformation) != 0;
                    viewSalInfo.Checked =
                        ((int) labRightsBitMask & (int) AccessRightBit.ViewSalaryInformation) != 0;
                    viewAccess.Checked =
                        ((int) labRightsBitMask & (int) AccessRightBit.ViewAccess) != 0;
                    viewPendingAgr.Checked =
                        ((int) labRightsBitMask & (int) AccessRightBit.ViewPendingAgreements) != 0;
                    viewProtInfo.Checked =
                        ((int) labRightsBitMask & (int) AccessRightBit.ViewProtocolInformation) != 0;
                    editProtInfo.Checked =
                        ((int) labRightsBitMask & (int) AccessRightBit.EditProtocolInformation) != 0;
                    manageProtInfo.Checked =
                        ((int) labRightsBitMask & (int) AccessRightBit.ManageProtocolInformation) != 0;
                    viewPeoplesoftInfo.Checked =
                        ((int) labRightsBitMask & (int) AccessRightBit.ViewPeoplesoftInformation) != 0;
                    viewUserOrder.Checked =
                        ((int) labRightsBitMask & (int) AccessRightBit.ViewUserOrder) != 0;
                    manageUserOrder.Checked =
                        ((int) labRightsBitMask & (int) AccessRightBit.ManageUserOrder) != 0;

                    annunciator.Message = string.Empty;
                }
            }
            else
            {
                agreementsRow.Visible = humansRow.Visible = purchasingRow.Visible = labAccess.Visible = false;
                annunciator.Message = "No access rights are assigned to the lab.";
            }
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Wires up events.
        /// </summary>
        /// <param name="e">Information accompanying the event itself.</param>
        protected override void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);

            objectCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }

        #endregion
    }
}